<?php
/*首页数据*/
namespace Admin\Model;
use Think\Model;
class ChannelModel extends Model {
    
    /**
     * 渠道修改
     */
    public function isEditQuDao($data){
        // 渠道表
        $channel_mdb = M('wayuser');
        $userid = session('lampzuo_id');
        if($data['geit'] == "1"){
            $data['camptrade_url'] = "";
            $data['identifyprove_url'] = "";
        }
        // 拼接插入数据
        $insert_data = [
            'name' => $data['username'],
            'company' => $data['compny'],
            'age' => $data['age'],
            'type' => $data['group'],
            'tel' => $data['phone'],
            'bank' => $data['bank'],
            'banker' => $data['banker'],
            'banknum' => $data['banknum'],
            'scenetype' => $data['geit'],
            'status' => 0,
            'admin_id'=>$userid,
            'occupation' => $data['occupation'],
            'identify' => strtolower($data['identify']),
            // 'identify_url' => $data['identify_url'],
            'groupphoto_url' => serializeMysql($data['groupphoto_url']),
            'identifyprove_url' => serializeMysql($data['identifyprove_url']),
            'camptrade_url' => serializeMysql($data['camptrade_url']),
            'otherdata_url' => serializeMysql($data['otherdata_url']),
            'channeltype'   => $data['channeltype'],
            'create_time'   => time(),
        ];
        // 写入数据
        $channel_res = $channel_mdb->where(array('id'=>$data['id']))->save($insert_data);
        if($channel_res) {
            return $channel_res;
        }else{
            return false;
        }
    }

    /**
     * 渠道添加
     * @param [type] $data [description]
     */
    public function ActionChannel($data) {
        // print_r($data);die;
        //渠道表
        $admin_db = M('admin');
    	$channel_mdb = M('wayuser');
        $newwaynum = '';
        $userid = session('lampzuo_id');
        $admins = $admin_db -> where(array('position' => 5,'test_sign'=>0)) -> select();
        $channelCount = $channel_mdb -> count();
        $adminCount = count($admins);
        $admin = $admins[$channelCount % $adminCount];
    	$insert_data = [
    		'waynum'=>$newwaynum,
            'name' => $data['username'],
            'age' => $data['age'],
    		'company' => $data['compny'],
    		'type' => $data['group'],
    		'tel' => $data['phone'],
    		'identify' => strtolower($data['identify']),
    		'bank' => $data['bank'],
    		'banker' => $data['banker'],
            'banknum' => $data['banknum'],
    		'status' => 0,
            'admin_id'=>$userid,
    		'occupation' => $data['occupation'],
            'identify_url' => $data['identify_url'],
            'identifyprove_url' => $data['identifyprove_url'],
            'groupphoto_url' => $data['groupphoto_url'],
            'camptrade_url' => $data['camptrade_url'],
            'channeltype'   => $data['channeltype'],
            'scenetype'   => $data['scenetype'],
    		'address'   => $data['address'],
    		'create_time'   => time(),
            'auditor_id' => $admin['id'],
    	];


    	$channel_res = $channel_mdb->add($insert_data);
    	if($channel_res&&$this->record($channel_res,0,'创建渠道')) {
    		return $channel_res;
    	}else{
    		return false;
    	}
    }

    /**
     * 获取所有信息
     * field_arr   返回所需渠道表字段
     * $lr    分页处理
     */
    public function EchoAllChannel($field_arr=false,$where=false,$auth,$search) {
        // $channel_mdb = M('wayuser');
        $channel_mdb = M('sqfx_manage',null);
        $admin_mdb = M('admin');
        if($field_arr){
            $field_str = 'sqfx_manage.'.implode(',sqfx_manage.',$field_arr);
        }else{
            $field_str = true;
        }
        if(!empty($search)){
            $search = " and sqfx_manage.zsxm like '%{$search}%' OR sqfx_manage.zsxm like '%{$search}%' and ".trim($where,'where');
        }else{
            $search = '';
        }
       $count= $channel_mdb->where($where.$search)->count();
        // 实例化分页类 传入总记录数和每页显示的记录数(25)
       $Page = new \Think\Page($count,8);
       $channel_data = $channel_mdb
       ->where($where.$search)
       ->limit($Page->firstRow.','.$Page->listRows)
       ->field($field_str)
       ->select();
        // print_r($channel_data);die;
        $pageData=$Page->showAppAjax();
        return array('channel_data'=>$channel_data,'pageData'=>$pageData);
    }
    
    /**
     * 获取指定单挑数据
     * id  array  条件数组
     * field array 所需字段
     */
    public function OnefieldData($id=false,$field=false,$ands=false) {
        $channel_mdb = M('wayuser');
        if($field){
            $field = implode(',', $field);
        }else{
            $field = true;
        }
        if($id){
            $id_key = array_keys($id);
            $id_value = array_values($id);
            $where = $id_key[0].'="'.$id_value[0].'"';
            if($ands){
                if(count($ands)>1){
                    foreach ($ands as $field_key => $field_value) {
                        $where .= ' and '.$field_key.$field_value[0].$field_value[1];
                    }
                }else{
                    $ands_key = array_keys($ands);
                    $ands_value = array_values($ands);
                    $where .= ' and '.$ands_key[0].$ands_value[0][0].$ands_value[0][1];
                }
            }
        }else{
            return false;
        }
        $channel_data = $channel_mdb->where($where)->field($field)->find();
        if($channel_data){
            return $channel_data;
        }else{
            return false;
        }
    }

    /**
     * 获取渠道单数据信息列表
     */
    public function ChannelDetailsInfo($id) {
        $channel_mdb = M('wayuser');
        $myinfo_db = D('myinfo');
        $city_mdb = D('city');
        $channel_data = $channel_mdb->where('id ='.$id)->find();
        if(!$channel_data){
            return false; 
        }
        $admindata = $myinfo_db->OneFieldData($channel_data['admin_id'],['name','usernum','cityid','provinceid']);
        $admincity = $city_mdb->GetCityInfo($admindata['cityid'],'city_name')['name'];
        $adminprovince = $city_mdb->GetCityInfo($admindata['provinceid'],'city_name')['name'];
        $status = [
            '-1'=>'拒绝(未通过审核)',
            '0'=>'创建渠道(未审核)',
            '1'=>'待激活(城市已审核)',
            '2'=>'关闭渠道(已审核)',
            '3'=>'激活(风控已审核)'
        ];
        $channel_data['create_time'] = date('Y-m-d H:i:s',$channel_data['create_time']);
        $channel_data['activation_time'] = date('Y-m-d H:i:s',$channel_data['activation_time']);
        $channel_data['citymanager_time'] = date('Y-m-d H:i:s',$channel_data['citymanager_time']);
        $channel_data['admin_name'] = $admindata['name'];
        $channel_data['admin_id'] = $admindata['usernum'];
        $channel_data['admincity'] = $admincity;
        $channel_data['adminprovince'] = $adminprovince;
        $channel_data['status'] = $status[$channel_data['status']];
        return $channel_data;
    }

    /**
     * 获取所有信息
     * field_arr   返回所需渠道表字段
     */
    public function ListAllChannel($field_arr=false,$json_true=false) {
        $channel_mdb = M('wayuser');
        $myinfo_mdb  = D('myinfo');
        $admin_db   = M('admin');
        if($field_arr){
            $field_str = implode(',',$field_arr);
        }else{
            $field_str = true;
        }
        $userid        = session('lampzuo_id');
        $adminuserres  = $admin_db->where('id='.$userid)->find();
        if($adminuserres['position'] == "502"){
            $count= $channel_mdb->where('status=1')->count();
            $Page = new \Think\Page($count,15);
            $channel_data = $channel_mdb
            ->where('status=1')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->field($field_str)
            ->select();
        }else{
            // 查询满足要求的总记录数
            $count= $channel_mdb->where('status=1 and auditor_id='.$userid)->count();
            // 实例化分页类 传入总记录数和每页显示的记录数(25)
            $Page = new \Think\Page($count,15);
            $channel_data = $channel_mdb
            ->where('status=1 and auditor_id='.$userid)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->field($field_str)
            ->select();
        }
        $status = ['-2'=>'驳回（正在修改）','-1'=>'拒绝(未通过审核)','0'=>'创建渠道(未审核)','1'=>'待激活(城市已审核)','2'=>'激活状态(风控已审核)','3'=>'关闭状态(风控已审核)'];
        $channel_data_json = [];
        foreach ($channel_data as $key => $value) {
            $admindata = $myinfo_mdb->OneFieldData($value['admin_id'],['name','usernum']);
            $value['admin_name'] = $admindata['name'];
            $value['admin_id'] = $admindata['usernum'];
            $value['status'] = $status[$value['status']];
            $value['activation_time']  = date('Y-m-d H:i:s',$value['activation_time']);
            $value['citymanager_time'] = date('Y-m-d H:i:s',$value['citymanager_time']);
            $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            $channel_data[$key] = $value;
            if($json_true){
                $channel_data_json[] = ['id'=>$value['id'],'d'=>$value];
            }
        }

        if($json_true){
            return ['data'=>$channel_data_json,'page'=>$Page];
        }else{
            return ['data'=>$channel_data,'page'=>$Page];
        }
    }

    /**
     * 风控已操作的数据
     */
    public function FkAction($field_arr=false) {
        $channel_mdb = M('wayuser');
        $myinfo_mdb = D('myinfo');
        $admin_mdb = M('admin');
        $waoperation = M('wayuser_operation');
        if($field_arr){
            $field_str = implode(',',$field_arr);
        }else{
            $field_str = true;
        }
        $meid = session('lampzuo_id');
        $get_data = I('get.');
        
        $medata = $admin_mdb->where('id='.$meid)->find();
        if($medata['position']=='5'){
            $jt=strtotime(date("Y-m-d",strtotime("-3 day")).' '.date('H:i'));
            $now_time = strtotime("now");
            $where_query = 'jdc_wayuser.status<>1 
            and jdc_wayuser.status<>0 
            and jdc_wayuser.activation_time > '.$jt.' 
            and jdc_wayuser.activation_time<'.$now_time.' 
            and jdc_wayuser.auditorfk='.$meid;
        }else if($medata['position']=='501'){
            $where_query = 'jdc_wayuser.status<>1 
            and jdc_wayuser.status<>0';
        }else{
            $where_query = 'jdc_wayuser.status<>1 
            and jdc_wayuser.status<>0';
        }
        $screen = $get_data['screen'];
        
        $screenarr = ['1','2','3','4'];

        $screenarr_status = ['1'=>'2','2'=>'-1','3'=>'-2','4'=>'3'];

        if(!empty($screen)&&in_array($screen, $screenarr)) 
            $where_query .= ' and jdc_wayuser.status='.$screenarr_status[$screen];

        $key = $get_data['key'];
        if(!empty($key)) 
            $where_query .= ' and (jdc_wayuser.name like "%'.$key.'%" 
            or jdc_wayuser.waynum like "%'.$key.'%"  
            or jdc_admin.name like "%'.$key.'%" 
            or jdc_admin.usernum like "%'.$key.'%")';

        if(!empty($key)){
            $auditorfk = " or jdc_admin.id=jdc_wayuser.auditorfk";
        }else{
            $auditorfk =" ";
        }
        // 查询满足要求的总记录数
        $count= $channel_mdb->join('jdc_admin on jdc_admin.id=jdc_wayuser.admin_id'.$auditorfk)->where($where_query)->count();
        // 实例化分页类 传入总记录数和每页显示的记录数
        $Page = new \Think\Page($count,15);
        $channel_data = $channel_mdb->where($where_query)
        ->join('jdc_admin on jdc_admin.id=jdc_wayuser.admin_id'.$auditorfk)
        ->limit($Page->firstRow.','.$Page->listRows)
        ->order('jdc_wayuser.create_time desc')
        ->field($field_str)
        ->select();
        $status = ['-2'=>'驳回(正在修改）','-1'=>'拒绝(未通过审核)','0'=>'创建渠道(未审核)','1'=>'待激活(城市已审核)','2'=>'激活状态(风控已审核)','3'=>'关闭状态(风控已审核)'];

        $channel_data_json = [];
        foreach ($channel_data as $key => $value) {
            $admindata = $myinfo_mdb->OneFieldData($value['admin_id'],['name','usernum']);
            $medataarr = $admin_mdb->where('id='.$value['auditorfk'])->find();
            $value['admin_name'] = $admindata['name'];
            $value['admin_username'] = $medataarr['name'];
            $value['admin_usernum'] = $medataarr['usernum'];

            $value['admin_id'] = $admindata['usernum'];

            $value['status'] = $status[$value['status']];

            $value['activation_time'] = date('Y-m-d H:i:s',$value['activation_time']);

            $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            
            $channel_data[$key] = $value;
        }
        // echo "<pre>";
        // print_r($channel_data);die;
        return ['data'=>$channel_data,'page'=>$Page];
    }

    /**
     * 获取制定条件多条数据
     */
    public function DataWhere($id=false,$field=false) {
        $channel_mdb = M('wayuser');
        if($field){
            $field = implode(',', $field);
        }else{
            $field = true;
        }
        if($id){
            $id_key = array_keys($id);
            $id_value = array_values($id);
            $where = $id_key[0].'='.$id_value[0];
        }else{
            return false;
        }
        $channel_data = $channel_mdb
        ->where($where)
        ->field($field)
        ->select();
        if($channel_data){
            return $channel_data;
        }else{
            return false;
        }
    }

    /**
     * 获取指定渠道所能关联的单数
     * $id   渠道数据ID
     * $type.  danshu(单数) yuqi(逾期单数) zongjine(订单总金额) fenrun(分润总金额)
     * $type.  beiju(被拒绝订单)
     * $where_field. 查询条件字段
     */
    public function OneRelationCount($id=false,$type,$where_field=false) {
        //当前时间
        $time = time();
        $channel_mdb = M('wayuser');
        $user_mdb = M('user');
        $order_mdb = M('order');
        $admin_mdb = M('admin');
        $order_db = D('Order');
        $orderPay_mdb = M('order_pay');
        $sqfx = M('sqfx_manage',null);
        $meid = session('lampzuo_id');
        $where_field = $where_field?$where_field:'id';
        // 渠道订单数
        if($type=='danshu'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }

            $userids = $user_mdb
            ->where('waynum='.$channel_one['waynum'])
            ->field('id')
            ->select();

            if(!$userids){
                return 0;
            }
            $userids = implode(',',array_column($userids, 'id'));

            $count_relation = $order_mdb->where('uid in('.$userids.')')->count();

            return $count_relation;
        // 逾期订单
        }else if($type=='yuqi'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$user_data){
                return 0;
            }
            $timeoutcount = [];
            foreach ($user_data as $key => $value) {
                $orderPay_one_data = $orderPay_mdb->where('uid='.$value['id'])->select();
                if(!$orderPay_one_data){
                    continue;
                }
                foreach ($orderPay_one_data as $k => $v) {
                    if(date('Ymd',$v['next_pay_time'])<date('Ymd',$time)){
                        $timeoutcount[$v['uid']] += 1;
                    }
                }
            }
            return array_sum($timeoutcount);
        // 总金额
        }else if($type=='zongjine'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $count_relation = [];
            foreach ($cha_user_data as $key => $value) {
                $orderPay_all_data = $orderPay_mdb->where('uid='.$value['id'])->select();
                foreach ($orderPay_all_data as $k => $v) {
                    $count_relation[$v['uid']] += $v['money'];
                }
            }
            return array_sum($count_relation);
        // 分润金额
        }else if($type=='fenrun'){
            $danshu = $this->OneRelationCount($id,'danshu');
            $zongjine = $this->OneRelationCount($id,'zongjine');
            if($danshu==0){
                return 0;
            }
            $fenrun = ($zongjine/$danshu)*C('FENRUN');
            return $fenrun;
            // 被拒订单
        }else if($type=='beiju'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $count_relation = [];
            foreach ($cha_user_data as $key => $value) {
                $count_relation[$value['id']] += $order_mdb->where('uid='.$value['id'].' and status=-1')->count();
            }
            return array_sum($count_relation);
            // 本月订单数
        }else if($type=='benyue_danshu'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $count_relation = [];
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            foreach ($cha_user_data as $key => $value) {
                $count_relation[$value['id']] += $order_mdb->where('uid='.$value['id'].' and create_time<'.$benyue_z.' and create_time>'.$benyue_a)->count();
            }
            return array_sum($count_relation);
        // 本月被拒订单数
        }else if($type=='benyue_beiju'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $count_relation = [];
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            foreach ($cha_user_data as $key => $value) {
                $count_relation[$value['id']] += $order_mdb->where('uid='.$value['id'].' and status=-1 and create_time<'.$benyue_z.' and create_time>'.$benyue_a)->count();
            }
            return array_sum($count_relation);
        // 上次做单时间
        }else if($type=='shangci_dan'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $relation = [];
            foreach ($cha_user_data as $key => $value) {
                $relation[$value['id']] = $order_mdb
                ->where('uid='.$value['id'])
                ->order('create_time desc')
                ->limit(1)
                ->field('create_time,id')
                ->find();
                continue;
            }
            if(!$relation){
                return false;
            }
            $create_time=array();
            foreach($relation as $v){
                $create_time[]=$v["create_time"];
            }
            array_multisort($create_time, SORT_ASC, $relation);
            return date('Y-m-d H:i:s',array_pop($relation)['create_time']);
        // 成功单数
        }else if($type=='chenggongdan'){
            $channel_data = $channel_mdb->where($id)->select();
            if(!$channel_data){
                return 0;
            }
            $chenggong = 0;
            foreach ($channel_data as $key => $value) {
                 $user_data = $user_mdb
                 ->where('waynum='.$value['waynum'])
                 ->field('id')
                 ->select();
                 if(!$user_data){
                    continue;
                 }
                 foreach ($user_data as $k => $v) {
                     $chenggong+=$order_db->OrderCount(['uid'=>['eq',$v['id']]],'chenggong');
                 }
            }
           return $chenggong;
        // 本月成功单数
        }else if($type=='benyue_chenggong'){
            $channel_data = $channel_mdb->where($id)->select();
            if(!$channel_data){
                return 0;
            }
            $chenggong = 0;
            foreach ($channel_data as $key => $value) {
                 $user_data = $user_mdb
                 ->where('waynum='.$value['waynum'])
                 ->field('id')
                 ->select();
                 if(!$user_data){
                    continue;
                 }
                 foreach ($user_data as $k => $v) {
                     $chenggong+=$order_db->OrderCount(['uid'=>['eq',$v['id']]],'benyue_chenggong');
                 }
            }
           return $chenggong;
        //所属地区
        }else if($type=='suoshu_city'){
            $admin_data = $admin_mdb
            ->join('jdc_city c on c.id=jdc_admin.cityid')
            ->where('jdc_admin.id='.$id)
            ->find();
            return $admin_data['name'];
        // 渠道激活量
        }else if($type=='jihuoliang'){
            $admin_data = $admin_mdb->where('id='.$meid)->field('position,provinceid,id')->find();
            if($admin_data['position']=='1'){
                $where = 'admin_id='.$meid.' and zt=1';
                $admincount = $sqfx->where($where)->count();
            }else if($admin_data['position']=='3'){
                $adminids = M('admin')
                ->where('mid='.$admin_data['id'].$this->istest['testsql'])
                ->field('id')->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'zt=1  and admin_id in('.$adminids.')';
                $admincount = $sqfx->where($where)->count();
            }else if($admin_data['position']=='4'){
                $adminids = M('admin')
                ->where('provinceid='.$admin_data['provinceid'].$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'admin_id in('.$adminids.') and zt=1';
                $admincount = $sqfx->where($where)->count();
            }else if($admin_data['position']=='1100'){
                $adminids = M('admin')
                ->where('1=1'.$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'admin_id in('.$adminids.') and zt=1';
                $admincount = $sqfx->where($where)->count();

            }
            return $admincount;
        // 渠道总数量
        }else if($type=='qudaozongl'){
            $admin_data = $admin_mdb
            ->where('id='.$meid)
            ->field('position,provinceid,id')
            ->find();
            $where = '';
            if($admin_data['position']=='1'){
                // return $channel_mdb->where('admin_id='.$meid)->count();
                return $admincount = $sqfx->where('admin_id='.$meid)->count();
            }else if($admin_data['position']=='3'){
                $adminids = $admin_mdb
                ->where('mid='.$admin_data['id'].$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'admin_id in('.$adminids.')';

            }else if($admin_data['position']=='4'){
                $adminids = M('admin')
                ->where('provinceid='.$admin_data['provinceid'].$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'admin_id in('.$adminids.')';
            }
            return $admincount = $sqfx->where($where)->count();
            // return $channel_mdb->where($where)->count();
        // 待审核渠道
        }else if($type=='daishen'){
            $admin_data = $admin_mdb
            ->where('id='.$meid)
            ->field('position,provinceid,id')
            ->find();
            if($admin_data['position']=='1'){
                $where = 'admin_id='.$meid.' and zt=0';
            }else if($admin_data['position']=='3'){
                $adminids = M('admin')
                ->where('mid='.$admin_data['id'].$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'zt=0 and admin_id in('.$adminids.')';
            }else if($admin_data['position']=='4'){
                $adminids = $admin_mdb
                ->where('provinceid='.$admin_data['provinceid'].$this->istest['testsql'])
                ->field('id')
                ->select();
                if(!$adminids){
                    return 0;
                }
                $adminids = implode(',',array_column($adminids, 'id'));
                $where = 'zt=0 and admin_id in('.$adminids.')';
            }
            return $sqfx->where($where)->count();
            return false;
        // 总通过率
        }else if($type=='ztongguolu'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $uids = array_column($cha_user_data,'id');
            $ids = implode(',',$uids);
            $count_relation = $order_mdb->where('status=6 and uid in('.$ids.')')->count();
            return $count_relation;
        // 月通过率
        }else if($type=='yuetongguolu'){
            $channel_one = $channel_mdb->where($where_field.'='.$id)->find();
            if(!$channel_one){
                return 0;
            }
            $cha_user_data = $user_mdb->where('waynum='.$channel_one['waynum'])->select();
            if(!$cha_user_data){
                return 0;
            }
            $uids = array_column($cha_user_data,'id');
            $ids = implode(',',$uids);
            $date = date('Y-m-d');
            $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
            $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
            $benyue_a = strtotime($benyue_a);
            $count_relation = $order_mdb
            ->where('status=6 and uid in('.$ids.') and create_time<'.$benyue_z.' and create_time>'.$benyue_a)
            ->count();
            return $count_relation;
        }
    }

    /**
     * 获取所有数据
     */
    public function ordercount_channel($adminid,$cl) {
        // 当前时间
        $time = time();
        $channel_mdb = M('wayuser');
        $user_mdb = M('user');
        $order_mdb = M('order');
        $orderpay_mdb = M('order_month_pay');
        $orderop_mdb = M('order_operation');
        $admin_mdb = M('admin');
        $admindata = $admin_mdb->where('id='.$adminid)->find();
        $date = date('Y-m-d');
        $benyue_a = date('Y-m-01 00:00:00', strtotime($date));
        // 本月最后一天
        $benyue_z = strtotime(date('Y-m-d 23:59:59', strtotime("$benyue_a +1 month -1 day")));
        // 本月第一天
        $benyue_a = strtotime($benyue_a);
        // 今天 00 点的时间戳
        $down_time = strtotime(date('Ymd',$time));
        switch ($cl) {
            // 总单量
            case 'ordercount':
                $where = "";
                break;
            // 总成功单量
            case 'allsuccess':
                $where = ' and status=6';
                break;
            // 总被拒绝单量
            case 'allrefuse':
                $where = ' and status=-1';
                break;
            // 月单量
            case 'month_ordercount':
                $where = ' and create_time<'.$benyue_z.' and create_time>'.$benyue_a;
                break;
            // 月被成功单量
            case 'month_success':
                $where = ' and status=6 and create_time<'.$benyue_z.' and create_time>'.$benyue_a;
                break;
            // 月被拒绝单量
            case 'month_refuse':
                $where = ' and status=-1 and create_time<'.$benyue_z.' and create_time>'.$benyue_a;
                break;
            // 逾期单数
            case 'yuqi':
                if($admindata['position']=='3'){
                    $adminids = $admin_mdb->where('pid='.$admindata['id'].$this->istest['testsql'])->field('id')->select();
                    if(!$adminids){
                        return 0;
                    }
                    $adminids = implode(',',array_column($adminids, 'id'));
                    $userid = '1=1 and  id  in('.$adminids.')';
                    $adm = M('admin')->where($userid)->select();
                    for($i = 0; $i < count($adm); $i++){
                          if($s){
                              $s.=",'".$adm[$i]['usernum']."'";
                          }else{
                              $s.="'".$adm[$i]['usernum']."'";
                          }
                    }
                    $usernums = '1=1 and  usernum  in ('.$s.')';
                    $operation = M('order_operation')->where($usernums)->select();
                    $orderids = implode(',',array_column($operation, 'orderid'));
                    $position_sql = ' and orderid in('.$orderids.')';
                }else{
                    $position_sql = '';
                }

                $orderpay_ids = $orderpay_mdb->where('status = 0 and pay_time<'.$down_time.$position_sql)->field('orderid ')->select();
                if(!$orderpay_ids){
                    return 0;
                }

                $orderpay_ids = implode(',',array_column($orderpay_ids,'orderid'));

                $where = ' and orderid in('.$orderpay_ids.')';
                break;
            default:
                return false;
        }
        // 顾问
        if($admindata['position']==1){
            $orderids = $orderop_mdb->where('usernum="'.$admindata['usernum'].'" and status=0')->select();
            if(!$orderids){
                return 0;
            }
            $orderids = implode(',',array_column($orderids, 'orderid'));
            $count_relation = $order_mdb
            ->where('orderid in('.$orderids.')'.$where)
            ->count();
        // 城市经理
         }else if($admindata['position']==3){
            $adminids = $admin_mdb->where('pid='.$admindata['id'].$this->istest['testsql'])->field('id')->select();
            if(!$adminids){
                return 0;
            }
            $adminids = implode(',',array_column($adminids, 'id'));
            $userid = '1=1 and  id  in('.$adminids.')';
            $adm = M('admin')->where($userid)->select();
            for($i = 0; $i < count($adm); $i++){
                  if($s){
                      $s.=",'".$adm[$i]['usernum']."'";
                  }else{
                      $s.="'".$adm[$i]['usernum']."'";
                  }
            }
            $usernums = '1=1 and  usernum  in ('.$s.')';
            $operation = M('order_operation')->where($usernums)->select();
            $orderids = implode(',',array_column($operation, 'orderid'));
            if(!$orderids){
                return 0;
            }
            $position_sql = ' and orderid in('.$orderids.')';
            $count_relation = $order_mdb->where('1=1'.$position_sql.$where)->count();


        // 省总
         }else if($admindata['position'] == 4){
            $count_relation = $order_mdb->where('provinceid='.$admindata['provinceid'].$where)->count();
        // 全国
         }else if($admindata['position'] == 1100){
            $count_relation = $order_mdb->where("1=1".$where)->count();
         }else{
            $count_relation = 0;
         }
         return $count_relation;
    }   

    /**
     * 修改渠道信息
     * $id.  id
     * $data. array 需要修改的字段名及对应数据
     */
    public function EditChannelData($id,$data) {
        $channel_mdb = M('wayuser');
        if($id){
            $id_key = array_keys($id);
            $id_value = array_values($id);
            $where = $id_key[0].'='.$id_value[0];
        }else{
            return false;
        }
        $edit_res = $channel_mdb->where($where)->save($data);
        if($edit_res){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 渠道状态返回
     */
    public function statuschannel($n) {
        $arr  = ['-2'=>'驳回(正在修改）','-1'=>'拒绝(未通过审核)','0'=>'创建渠道(未审核)','1'=>'待激活(城市已审核)','2'=>'激活状态(风控已审核)','3'=>'关闭状态(风控已审核)'];
        return $arr[$n];
    }
    
    /**
     * 记录渠道操作
     * @param int wayuserid渠道ID
     * @param int usernum操作员的工号
     * @param int status改变的状态
     * @param string remark备注修改的说明
     */
    public function record($wayuserid,$status,$remark) {
        if(!session('?lampzuo_id')) return false;
        $meid = session('lampzuo_id');
        $admindata = M('admin')->where('id='.$meid)->field('id,usernum,position,provinceid,cityid')->find();
        if(!$admindata) return false;
        $time = time();
        $channel_action = M('wayuser_operation');
        $insertData['usernum'] = $admindata['usernum'];
        $insertData['wayuserid'] = $wayuserid;
        $insertData['status'] = $status;
        $insertData['remark'] = $remark;
        $insertData['create_time'] = $time;
        $actio_res = $channel_action->add($insertData);
        if($actio_res){
            return $actio_res;
        }else{
            return false;
        }
    }
}